<template>
  <div style="margin-top: 50px;margin-left:100px">
    <!-- :rules="rules" -->
    <el-form :model="value" ref="productInfoForm" label-width="120px" style="width: 600px" size="small">
      <el-form-item label="商品分类：" prop="productCategoryId">
        <el-cascader
          v-model="selectProductCateValue"
          :options="productCateOptions">
        </el-cascader>
        <el-button size="small" @click="isNewProductCateOpen=true" type="primary">新增分类</el-button>
      </el-form-item>
      <el-form-item label="商品名称：" prop="name">
        <el-input v-model="value.name"></el-input>
      </el-form-item>
      <el-form-item label="副标题：" prop="subTitle">
        <el-input v-model="value.subTitle"></el-input>
      </el-form-item>
      <el-form-item label="商品品牌：" prop="brandId">
        <el-select
          v-model="value.brandId"
          @change="handleBrandChange" filterable :filter-method="getReallyYouWant"
          placeholder="请选择品牌">
          <el-option
            v-for="item in brandOptionsCopy"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button size="small" @click="isNewProductBrandOpen=true" type="primary">新增品牌</el-button>
      </el-form-item>

      <el-form-item label="商品货号：">
        <el-input v-model="value.productSn"></el-input>
      </el-form-item>
      <el-form-item label="商品售价：">
        <!-- <el-input v-model="value.price"></el-input> -->
        <el-input v-model="value.price"></el-input>
      </el-form-item>
      <el-form-item label="市场价：">
        <!-- <el-input v-model="value.originalPrice"></el-input> -->
        <el-input v-model="value.originalPrice"></el-input>
      </el-form-item>
      <el-form-item label="展示销量：">
        <el-input v-model="value.showSale"></el-input>
      </el-form-item>
      <!-- 商品库存会按照sku每个仓库的库存进行计算，所以这里不需要再手动维护 -->
      <!-- 客户让加上的。。。 -->
      <!-- <el-form-item label="商品总库存：" v-if="isEdit">
        <el-input v-model="value.stock" :disabled="isEdit"></el-input>
      </el-form-item> -->
      <el-form-item label="计量单位：">
        <el-input v-model="value.unit"></el-input>
      </el-form-item>
     
      <el-form-item label="商品重量：">
        <el-input v-model="value.weight" style="width: 300px"></el-input>
        <span style="margin-left: 20px">克</span>
      </el-form-item>
      <!-- spu的仓库信息，根据sku选择的仓库进行传值，这里不再进行操作 -->
      <!-- <el-form-item label="选择仓库" required >
        <el-select v-model="value.depotProductList" multiple :multiple-limit="2" placeholder="请选择">
          <el-option
            v-for="item in value.depotList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="排序">
        <el-input v-model="value.sort"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleNext('productInfoForm')">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="新增商品分类" :visible.sync="isNewProductCateOpen" :before-close="getProductCateList" class="adjustmentBox">
     <product-cate-detail :is-edit='false'></product-cate-detail>
    </el-dialog>
    <el-dialog title="新增商品品牌" :visible.sync="isNewProductBrandOpen" :before-close="getBrandList" class="adjustmentBox">
     <brand-detail :is-edit='false'></brand-detail>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchListWithChildren} from '@/api/productCate'
  import {fetchList as fetchBrandList} from '@/api/brand'
  import {getProduct} from '@/api/product';
  // import {fetchList as fetchDepotList} from '@/api/depository'
  import ProductCateDetail from '../../productCate/components/ProductCateDetail'
  import BrandDetail from '../../brand/components/BrandDetail'
  export default {
    name: "ProductInfoDetail",
    components:{ProductCateDetail,BrandDetail},
    props: {
      value: Object,
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        isNewProductBrandOpen:false,//新增商品品牌的弹窗
        isNewProductCateOpen:false,//新增商品分类的弹窗
        hasEditCreated:false,
        selectProductCateValue: [], //选中商品分类的值
        productCateOptions: [],
        brandOptions: [],
        brandOptionsCopy:[],//搜索用的
        rules: {
          name: [
            {required: true, message: '请输入商品名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          subTitle: [{required: true, message: '请输入商品副标题', trigger: 'blur'}],
          productCategoryId: [{required: true, message: '请选择商品分类', trigger: 'blur'}],
          brandId: [{required: true, message: '请选择商品品牌', trigger: 'blur'}],
          description: [{required: true, message: '请输入商品介绍', trigger: 'blur'}],
          requiredProp: [{required: true, message: '该项为必填项', trigger: 'blur'}]
        },
        cateParentId:null,//一级分类id
        productCategoryId:null,//二级分类id
        // depotList:[],//仓库列表
      };
    },
    created() {
      this.getProductCateList();
      this.getBrandList();
      // this.getDepotList();
      // if(this.isEdit){
      //   console.log("ahsidsgchaidja$$$$$$$$$$$$$");
      //   if(this.value.cateParentId !=null &&  this.value.productCategoryId!=null){
      //     this.selectProductCateValue.push(this.value.cateParentId);
      //     this.selectProductCateValue.push(this.value.productCategoryId);
      //   }
      //   console.log("this.selectProductCateValue: ");
      //   console.log(this.selectProductCateValue);
      // }
    },
    computed:{
      //商品的编号
      productId(){
        return this.value.id;
      }
    },
    watch: {
      value:{
        handler:function(newVal,oldVal){
          if(newVal.cateParentId !=null &&  newVal.productCategoryId!=null){
            let tempArr=[];
            tempArr.push(newVal.cateParentId);
            tempArr.push(newVal.productCategoryId);
            this.selectProductCateValue =JSON.parse(JSON.stringify(tempArr));
          }
        },
        immediate:true,//关键
        deep:true
      },
      productId:function(newValue){
        if(!this.isEdit)return;
        if(this.hasEditCreated)return;
        if(newValue===undefined||newValue==null||newValue===0)return;
        this.handleEditCreated();
      },
      selectProductCateValue: function (newValue) {
        if (newValue != null && newValue.length === 2) {
          this.cateParentId = newValue[0];
          this.productCategoryId = newValue[1];
         // this.value.productCategoryName= this.getCateNameById(this.value.productCategoryId);
        } else {
          this.cateParentId = null;
          this.productCategoryId = null;
          //this.value.productCategoryName=null;
        }
      }
    },
    methods: {
      //品牌的筛选
      getReallyYouWant(e){
        console.log(e);
        let keyword = e;
        if(keyword){
          let finalArr =[];
          this.brandOptions.map(item=>{
            if(item.label.startsWith(keyword)){
              finalArr.push(item);
            }
          })
          this.brandOptionsCopy = finalArr;
          this.$forceUpdate();
        }else{
          //复原
          this.brandOptionsCopy = JSON.parse(JSON.stringify(this.brandOptions));
        }
      },
      //处理编辑逻辑
      handleEditCreated(){
        console.log("yes")
        if(this.value.cateParentId !=null &&  this.value.productCategoryId!=null){
          this.selectProductCateValue.push(this.value.cateParentId);
          this.selectProductCateValue.push(this.value.productCategoryId);
        }
        this.hasEditCreated=true;
      },
      getProductCateList() {
        fetchListWithChildren().then(response => {
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
        this.isNewProductCateOpen = false;
      },
      getBrandList() {
        fetchBrandList({pageNum: 1, pageSize: 1000}).then(response => {
          this.brandOptions = [];
          let brandList = response.data.list;
          for (let i = 0; i < brandList.length; i++) {
            this.brandOptions.push({label: brandList[i].name, value: brandList[i].id});
          }
          this.brandOptionsCopy = JSON.parse(JSON.stringify(this.brandOptions));
        });
        this.isNewProductBrandOpen= false;
      },
      // getDepotList(){
      //   let self = this;
      //   fetchDepotList().then(res=>{
      //     if(res.code ==200){
      //       self.depotList = res.data;
      //     }
      //   })
      // },
      getCateNameById(id){
        let name=null;
        for(let i=0;i<this.productCateOptions.length;i++){
          for(let j=0;j<this.productCateOptions[i].children.length;j++){
            if(this.productCateOptions[i].children[j].value===id){
              name=this.productCateOptions[i].children[j].label;
              return name;
            }
          }
        }
        return name;
      },
      handleNext(formName){
         this.value.cateParentId = this.cateParentId;
            this.value.productCategoryId = this.productCategoryId;
        this.$refs[formName].validate((valid) => {
          if (valid) {
           
            this.$emit('nextStep');
          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      handleBrandChange(val) {
        let brandName = '';
        for (let i = 0; i < this.brandOptions.length; i++) {
          if (this.brandOptions[i].value === val) {
            brandName = this.brandOptions[i].label;
            break;
          }
        }
        this.value.brandName = brandName;
        this.brandOptionsCopy = JSON.parse(JSON.stringify(this.brandOptions));
      }
    }
  }
</script>

<style scoped>
.adjustmentBox >>> .form-container{
    width: 100%;
  }
</style>
